<?php
/**
 * 错误处理类
 * Created by PhpStorm.
 * User: chenyu
 * Date: 18-7-3
 * Time: 下午9:01
 */
namespace app\components\exceptions;

use Yii;
use yii\web\ErrorHandler;

class ExceptionHandler extends ErrorHandler
{
    use Handle;
    /** @var \Exception */
    protected $currentException;//当前异常对象

    /**
     * 重写渲染异常页面方法
     * @param type $exception
     */
    public function renderException($e)
    {
        $this->currentException=$e;
        //异常类有handle，调用自己的handle处理异常
        if(method_exists($this->currentException,'handle')){

            return $this->currentException->handle($this->currentException);
        }else{
            return $this->systemHandle();
        }

    }

    /**
     * 系统处理异常
     */
    protected function systemHandle()
    {
        if (YII_DEBUG) {
            $this->handle($this->currentException);
        }else{
            $this->handleExceptionWhenDebugOff();
        }
    }

    /**
     * debug 关闭的时候异常处理，输出固定信息，记录日志
     * @param $e
     */
    protected function handleExceptionWhenDebugOff()
    {
        $exception=[
            'code' => $this->currentException->getCode(),
            'msg'  => $this->currentException->getMessage(),
            'file'    => $this->currentException->getFile(),
            'line'   => $this->currentException->getLine()
        ];

        //记录日志
        Yii::info($exception, 'Exception');

        //展示异常信息
        $this->showMessage(-1, '系统异常');
    }

}